package com.example.day16_mp;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.NotificationTarget;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class BlankFragment extends Fragment {
    List<Music.DataBean> list = new ArrayList<>();
    MusicAdapter musicAdapter;
    private ListView lvNet;
    //activity中的控件
    private ImageView picUrl;
    private TextView name;
    private TextView singer;
    private ImageView pre,play,next;

    MyReceiver receiver;


    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_blank, container, false);
        initView(view);

        musicAdapter = new MusicAdapter(list,getContext());
        lvNet.setAdapter(musicAdapter);
        new MyTask().execute("http://10.161.9.80:7004/song/json?singer=%E9%82%93%E7%B4%AB%E6%A3%8B");

        //点击放歌
        lvNet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MusicUtils.getInstance().play(position);
                //下方的图片和文字发生变化
                change();
                sendNoti(1);
            }
        });
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicUtils.getInstance().playOrPause(play);
                sendNoti(2);
            }
        });
        pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicUtils.getInstance().pre();
                //下方的图片和文字发生变化
                change();
                sendNoti(1);
            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicUtils.getInstance().next();
                //下方的图片和文字发生变化
                change();
                sendNoti(1);
            }
        });
        receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bw.pre");
        intentFilter.addAction("com.bw.play");
        intentFilter.addAction("com.bw.next");
        getActivity().registerReceiver(receiver,intentFilter);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    @SuppressLint({"RemoteViewLayout", "UnspecifiedImmutableFlag"})
    private void sendNoti(int i) {
        NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        RemoteViews remoteViews = new RemoteViews(getActivity().getPackageName(),R.layout.noti_diy);
        remoteViews.setTextViewText(R.id.name,MusicUtils.getInstance().getName());
        remoteViews.setTextViewText(R.id.singer,MusicUtils.getInstance().getSinger());
        if(i==1){//点击放歌或者切歌时，自动显示暂停图标
            remoteViews.setImageViewResource(R.id.iv_play,R.drawable.baseline_pause_circle_outline_24);
        }else{//点击播放或者暂停按钮时，调用图片的变化
            if(MusicUtils.getInstance().isPlaying()){//当前是播放状态还是暂停状态
                remoteViews.setImageViewResource(R.id.iv_play,R.drawable.baseline_pause_circle_outline_24);
            }else{
                remoteViews.setImageViewResource(R.id.iv_play,R.drawable.baseline_play_circle_outline_24);
            }
        }
        //点击通知上的图片 发送广播
        {
            Intent intent = new Intent();
            intent.setAction("com.bw.pre");
            PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 103, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.iv_pre,broadcast);
        }
        {
            Intent intent = new Intent();
            intent.setAction("com.bw.play");
            PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 104, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.iv_play,broadcast);
        }
        {
            Intent intent = new Intent();
            intent.setAction("com.bw.next");
            PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 105, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.iv_next,broadcast);
        }

        Intent intent = new Intent(getActivity(), MainActivity2.class);
        intent.putExtra("type","1");//为了拉起服务时，能够初始下方的图片
        PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(),102,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(getActivity())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCustomContentView(remoteViews)
                .setContentIntent(pendingIntent)//拉起服务
                ;
        //版本控制
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            manager.createNotificationChannel(new NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT));
            builder.setChannelId("id");
        }
        Notification notification = builder.build();
        manager.notify(1,notification);
        NotificationTarget target = new NotificationTarget(getActivity(), R.id.picUrl, remoteViews, notification, 1);
        Glide.with(getActivity())
                .asBitmap()
                .load(MusicUtils.getInstance().getPicUrl())
                .into(target);

    }

    private void change() {
        name.setText(MusicUtils.getInstance().getName());
        singer.setText(MusicUtils.getInstance().getSinger());
        Glide.with(getContext()).load(MusicUtils.getInstance().getPicUrl()).into(picUrl);
        play.setImageResource(R.drawable.baseline_pause_circle_outline_24);//播放时图标换成暂停的
    }

    private void initView(View view) {
        lvNet = (ListView) view.findViewById(R.id.lv_net);
        picUrl = getActivity().findViewById(R.id.picUrl);
        //初始activity中的控件
        name = getActivity().findViewById(R.id.name);
        singer = getActivity().findViewById(R.id.singer);
        pre = getActivity().findViewById(R.id.iv_pre);
        play = getActivity().findViewById(R.id.iv_play);
        next = getActivity().findViewById(R.id.iv_next);
    }

    class MyTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... strings) {
            return HttpUtils.getInstance().doget(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s!=""){
                Music music = new Gson().fromJson(s, Music.class);
                list.addAll(music.getData());
                MusicUtils.getInstance().setList(music.getData());//没有这一行，放歌放不了
                musicAdapter.notifyDataSetChanged();
            }
        }
    }
    //定义广播接受者，处理广播
    class MyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bw.pre".equals(intent.getAction())){
                //执行上一首
                MusicUtils.getInstance().pre();//歌曲发生变化
                change();//页面中下方播放内容发生变化
                sendNoti(1);//通知界面内容发生变化
            }else if("com.bw.next".equals(intent.getAction())){
                MusicUtils.getInstance().next();
                change();//页面中下方播放内容发生变化
                sendNoti(1);//通知界面内容发生变化
            }else if("com.bw.play".equals(intent.getAction())){
                MusicUtils.getInstance().playOrPause(play);
                sendNoti(2);//控制上播放暂停的图片发生变化
            }
        }
    }
}